import {
  chunkArray,
  sendMessage,
  executeSequentially,
  awaitDelayTime,
  sleep,
  calculateMaxInputAmountOptimized,
  parseDateTimeToTs,
  formatTsToDateTime,
  getCurrentTimeText,
} from "../../utils";
import type { TManualVerifyGoods } from "../../type";
import CurrencyConverter from "../../currencyConverter";
import {
  deleteSkc,
  parsePrice,
  findDeleteButton,
  getErpSkuPriceMap,
  showCustomDialog,
} from "./utils";
import ConcurrentExecutor from "../../class/ConcurrentExecutor";

const concurrentExecutor = new ConcurrentExecutor(1);
const converter = new CurrencyConverter();
const originUrl = location.origin;

function getNextElement() {
  const nextElement = document.querySelector<HTMLElement>(
    ".so-pagination .so-pagination-item-ltr:last-child"
  );
  return nextElement;
}

function checkHasNextPage() {
  const nextElement = getNextElement();
  if (!nextElement) {
    return false;
  }
  return !nextElement.hasAttribute("disabled");
}

function doNextPage() {
  const nextElement = getNextElement();
  if (nextElement) {
    nextElement.click();
  }
}

function getRowInputId(tr: Element) {
  const trInput = tr.querySelector(".so-checkinput-checkbox-container input");
  if (!trInput) {
    return "";
  }

  const currentKey = trInput.getAttribute("id");
  return currentKey || "";
}
function getTableRowDateRowKey() {
  const tableBody = document.querySelector(".so-table");
  if (!tableBody) {
    return "";
  }

  const firstRow = tableBody.querySelector(
    ".so-scroll-inner .so-table-table-bordered .so-table-normal"
  );
  if (!firstRow) {
    return "";
  }
  return getRowInputId(firstRow);
}
function scrollToTr(tr: HTMLElement) {
  const tbody = tr.closest(".so-scroll-inner");
  if (!tbody) return;
  const trRect = tr.getBoundingClientRect();
  const tbodyRect = tbody.getBoundingClientRect();
  const isVisible =
    trRect.top >= tbodyRect.top && trRect.bottom <= tbodyRect.bottom;

  if (isVisible) return;
  const trTop = tr.offsetTop;
  tbody.scrollTop = trTop;
}

function checkFirstRowKey(targetKey: string) {
  return new Promise((resolve, reject) => {
    let checkTimer: number;
    const timeoutId = setTimeout(() => {
      clearTimeout(checkTimer);
      reject("超过10秒还没翻页成功");
    }, 10000);

    const checkRow = () => {
      const currentKey = getTableRowDateRowKey();
      if (!currentKey) {
        checkTimer = setTimeout(checkRow, 1000);
        return;
      }

      if (currentKey !== targetKey) {
        clearTimeout(timeoutId);
        resolve(currentKey);
      } else {
        checkTimer = setTimeout(checkRow, 1000);
      }
    };
    checkRow();
  });
}

function getSkuCodeByElement(row: Element) {
  let skuCode = "";
  const skuCodeElement = row.querySelector('[class*="mrs_styles__sku--"]');
  if (skuCodeElement) {
    const match = skuCodeElement.textContent?.match(/SKU:\s([a-zA-Z0-9]+)/);

    if (match) {
      skuCode = match[1];
    }
  }
  return skuCode;
}

async function setReactInputValueBySheinPlatform(
  skuCode: string,
  value: number
): Promise<boolean> {
  return new Promise((resolve) => {
    chrome.runtime.sendMessage(
      {
        type: "setReactInputValueBySheinPlatform",
        skuCode,
        value,
      },
      (response) => {
        resolve(response?.success || false);
      }
    );
  });
}

function findPreviousDeleteButton(trElement: Element) {
  // 如果自己有直接返回
  const currentRowFixedRightCell = trElement.querySelector(
    ".so-table-fixed-right,.so-table-fixed-first"
  );

  if (currentRowFixedRightCell) {
    const deleteButton = findDeleteButton(currentRowFixedRightCell);
    if (deleteButton) return deleteButton;
  }

  // 获取当前tr的前一个兄弟元素
  let previousTr = trElement.previousElementSibling;
  // 循环查找前一个兄弟元素
  while (previousTr) {
    const fixedRightCell = previousTr.querySelector(
      ".so-table-fixed-right,.so-table-fixed-first"
    );

    if (fixedRightCell) {
      const deleteButton = findDeleteButton(fixedRightCell);
      if (deleteButton) return deleteButton;
    }

    previousTr = previousTr.previousElementSibling;
  }

  return false;
}

function findRowPriceInfo(trElement: Element) {
  if (!trElement) {
    return null;
  }
  const tds = trElement.getElementsByTagName("td");

  for (let i = 0; i < tds.length; i++) {
    const td = tds[i];
    const targetDiv = td.querySelector("div.so-button-group");

    if (targetDiv && i > 0) {
      const priceTd = tds[i - 1];
      return parsePrice(priceTd.textContent || "");
    }
  }

  return null;
}

async function formatSkuListToSkuInfoMap({
  skuInfoMap,
  platform,
  shopId,
  multiplierMinInput,
  multiplierMaxInput,
  operateMap = {},
}: {
  skuInfoMap: any;
  platform: string;
  shopId: string;
  multiplierMinInput: number;
  multiplierMaxInput: number;
  operateMap: any;
}): Promise<void> {
  const storage = await chrome.storage.sync.get(["baoyiplus_accessToken"]);
  const { baoyiplus_accessToken = "" } = storage;
  if (baoyiplus_accessToken) {
    const skuInfoRowList = document.querySelectorAll(
      ".so-scroll-inner .so-table-table-bordered .so-table-normal"
    );
    const skuInfoRowMap: any = {};
    const skuCodeList: any[] = [];
    Array.from(skuInfoRowList).forEach((row) => {
      const skuCode = getSkuCodeByElement(row);
      const { price, currency } = findRowPriceInfo(row) || {};

      const currentSkuDelete = findPreviousDeleteButton(row);

      const tableRowCheckboxInputId = getRowInputId(row);

      if (!(skuCode in operateMap) && skuCode && currentSkuDelete) {
        operateMap[skuCode] = true;
        skuCodeList.push(skuCode);
        skuInfoRowMap[skuCode] = {
          skuCode,
          currentSkuDelete,
          price,
          currency,
          tableRowCheckboxInputId,
          trElement: row,
        };
      }
    });
    let currentPageUseDelete = false;
    if (!skuCodeList.length) {
      return Promise.resolve();
    }

    const chunkSkuCodeList = chunkArray(skuCodeList, 50);

    const promiseArray: any[] = [];
    chunkSkuCodeList.forEach((skuCodeChunk) => {
      promiseArray.push(
        sendMessage({
          type: "getSkuPrice",
          data: {
            outId: `#in#${skuCodeChunk.join(",")}`,
            shopId,
          },
          platform,
          token: baoyiplus_accessToken,
        })
      );
    });

    return Promise.all(promiseArray).then((resList: any) => {
      const executeSequentiallyArray: any[] = [];
      const erpCodeInfoMap = resList.reduce((obj: any, res: any) => {
        (res?.data || []).forEach((record: any) => {
          const { outId, sourcePrice, sourceCurrency } = record;
          if (outId in skuInfoRowMap) {
            obj[outId] = {
              sourcePrice,
              sourceCurrency,
            };
          }
        });
        return obj;
      }, {});

      Object.keys(skuInfoRowMap).forEach((outId) => {
        const {
          currency,
          price,
          tableRowCheckboxInputId,
          currentSkuDelete,
          trElement,
        } = skuInfoRowMap[outId];
        if (outId in erpCodeInfoMap) {
          const { sourcePrice, sourceCurrency } = erpCodeInfoMap[outId];
          executeSequentiallyArray.push(async () => {
            const editInputPrice = await converter.convert(
              sourcePrice,
              sourceCurrency,
              currency
            );
            const finallyPrice = calculateMaxInputAmountOptimized({
              currencyPrice: Number(price),
              reduceRateRange: { min: 0.05, max: 0.8 }, // 这边不是范围而是最大值
              multiplierMinInput,
              multiplierMaxInput,
              purchasePrice: editInputPrice,
            });
            if (finallyPrice) {
              scrollToTr(trElement);
              return setReactInputValueBySheinPlatform(outId, finallyPrice);
            } else {
              if (!document.contains(currentSkuDelete)) {
                return Promise.resolve(true);
              }
              scrollToTr(trElement);
              currentPageUseDelete = true;
              return deleteSkc(currentSkuDelete);
            }
          });
        } else {
          executeSequentiallyArray.push(() => {
            if (!document.contains(currentSkuDelete)) {
              return Promise.resolve(true);
            }
            scrollToTr(trElement);
            currentPageUseDelete = true;
            return deleteSkc(currentSkuDelete);
          });
        }
      });

      return executeSequentially(executeSequentiallyArray).then(() => {
        if (currentPageUseDelete) {
          return formatSkuListToSkuInfoMap({
            skuInfoMap,
            platform,
            shopId,
            multiplierMinInput,
            multiplierMaxInput,
            operateMap,
          });
        }
        return Promise.resolve();
      });
    });
  } else {
    alert("登录已经过期，请先点击右上角重新登录");
    return Promise.reject("登录已经过期，请先点击右上角重新登录");
  }
}

async function manualVerifyPageGoods({
  multiplierMinInput = 1,
  multiplierMaxInput = 1,
  action,
  skuInfoMap,
  platform,
  shopId,
}: TManualVerifyGoods): Promise<{ action: string }> {
  try {
    await formatSkuListToSkuInfoMap({
      skuInfoMap,
      platform,
      shopId,
      multiplierMinInput,
      multiplierMaxInput,
      operateMap: {},
    });
    await awaitDelayTime();
    const currentKey = getTableRowDateRowKey();
    const hasNextPage = checkHasNextPage();
    if (!hasNextPage) {
      return Promise.resolve({
        action: "end",
      });
    }
    doNextPage();
    await checkFirstRowKey(currentKey);
    return Promise.resolve({
      action: "next",
    });
  } catch (error) {
    return Promise.reject(error);
  }
}

function findBtnGroupElement() {
  const btnGroupElement = document.querySelector('[class*="mrs_styles__btn--"');
  return btnGroupElement;
}
function findAddGoodsBtnElement() {
  const btnGroupElement = findBtnGroupElement();
  if (btnGroupElement) {
    // 找到 btnGroupElement 下 class 只有 "so-button so-button-primary" 的 button 元素
    const buttons = btnGroupElement.querySelectorAll("button");
    for (const btn of Array.from(buttons)) {
      if (
        btn.classList.length === 2 &&
        btn.classList.contains("so-button") &&
        btn.classList.contains("so-button-primary")
      ) {
        return btn;
      }
    }
  }
  return null;
}

function getGoodsList(params: any) {
  return fetch(
    `${originUrl}/mrs-api-prefix/promotion/simple_platform/query_goods`,
    {
      method: "POST",
      headers: {
        "Content-Type": "application/json",
      },
      body: JSON.stringify(params),
    }
  ).then((res) => {
    return res.json().then((resData) => {
      return resData;
    });
  });
}

function getSemiPlatformAddGoodsApiPayload() {
  return sendMessage({
    type: "getSemiPlatformAddGoodsApiPayload",
  });
}

function getSemiPlatformCreateActivePayload() {
  return sendMessage({
    type: "getSemiPlatformCreateActivePayload",
  });
}

async function getPayloadData() {
  const addGoodsBtn = findAddGoodsBtnElement();
  if (!addGoodsBtn) {
    alert("找不到添加商品按钮");
    return;
  }
  addGoodsBtn.click();
  let payloadData: Record<string, any> | null = null;
  for (let i = 0; i < 5; i++) {
    await sleep(1000);
    const { page_num, page_size, ...payload } =
      ((await getSemiPlatformAddGoodsApiPayload()) || {}) as Record<
        string,
        any
      >;
    if (payload && Object.keys(payload).length > 0) {
      payloadData = payload;
      const closeBtnElement = document.querySelector(
        ".so-modal-close"
      ) as HTMLElement;
      if (closeBtnElement) {
        closeBtnElement.click();
      }
      return payloadData;
    }
  }
  alert("未获取到有效的 payload，请稍后重试");
  return;
}

async function filterGoodsDataByErpPriceMap({
  enableGoodsData,
  shopId,
  platform,
  baoyiplus_accessToken,
  multiplierMinInput,
  multiplierMaxInput,
  isOnlyAddGoods,
}: {
  enableGoodsData: any[];
  shopId: string;
  platform: string;
  baoyiplus_accessToken: string;
  multiplierMinInput: number;
  multiplierMaxInput: number;
  isOnlyAddGoods: boolean;
}) {
  if (isOnlyAddGoods) {
    return Promise.resolve(enableGoodsData);
  }
  const skuCodeList = enableGoodsData.reduce((list, item) => {
    const { sku_info_list } = item;
    (sku_info_list || []).forEach((skuInfo: any) => {
      const sku = skuInfo.sku;
      if (sku) {
        list.push(sku);
      }
    });
    return list;
  }, []);
  const erpSKuPriceMap = await getErpSkuPriceMap({
    skuCodeList,
    shopId,
    platform,
    baoyiplus_accessToken,
  });

  if (!Object.keys(erpSKuPriceMap).length) {
    return [];
  }
  const list: any[] = [];
  const promiseArray = enableGoodsData.map((goods) => {
    return (async () => {
      const { supply_price_info: skc_supply_price_info, sku_info_list } = goods;
      let minRate = 0.2;
      let maxRate = 0.95;
      let skuCurrency = "";
      let currencyPrice = 0;
      if (skc_supply_price_info) {
        const {
          currency,
          supply_price,
          intercept_supply_price,
          max_supply_price,
        } = skc_supply_price_info;

        minRate = Number((intercept_supply_price / supply_price).toFixed(2));
        maxRate = Number((max_supply_price / supply_price).toFixed(2));
        currencyPrice = supply_price;
        skuCurrency = currency;
      }

      const skuFinallyPriceMap: any = {};

      const checkSkuCodePriceArray = sku_info_list.map((skuInfo: any) => {
        return (async () => {
          const { sku, supply_price_info: sku_supply_price_info } = skuInfo;
          const erpPriceInfo = erpSKuPriceMap[sku];
          if (!erpPriceInfo) {
            return;
          }
          if (!skc_supply_price_info) {
            if (sku_supply_price_info) {
              const {
                currency,
                supply_price,
                intercept_supply_price,
                max_supply_price,
              } = sku_supply_price_info;

              minRate = Number(
                (intercept_supply_price / supply_price).toFixed(2)
              );
              maxRate = Number((max_supply_price / supply_price).toFixed(2));
              currencyPrice = supply_price;
              skuCurrency = currency;
            } else {
              return;
            }
          }
          const { sourcePrice, sourceCurrency } = erpPriceInfo as any;
          const editInputPrice = await converter.convert(
            sourcePrice,
            sourceCurrency,
            skuCurrency
          );
          const finallyPrice = calculateMaxInputAmountOptimized({
            currencyPrice: Number(currencyPrice),
            reduceRateRange: { min: Number(minRate), max: Number(maxRate) }, // 这边不是范围而是最大值
            multiplierMinInput,
            multiplierMaxInput,
            purchasePrice: editInputPrice,
          });
          skuFinallyPriceMap[sku] = finallyPrice;
        })();
      });

      await Promise.all(checkSkuCodePriceArray);
      const skuPriceList = Object.values(skuFinallyPriceMap);
      const isAllSKuHaveFinallyPrice = skuPriceList.every((price) => !!price);
      if (skuPriceList.length && isAllSKuHaveFinallyPrice) {
        if (skc_supply_price_info) {
          list.push({
            ...goods,
            __finallyPrice: skuPriceList[0] || 0,
          });
        } else {
          const formatSkuInfoList = sku_info_list.map((skuInfoItem: any) => {
            const { sku } = skuInfoItem;
            return {
              ...skuInfoItem,
              __finallyPrice: skuFinallyPriceMap[sku] || 0,
            };
          });
          list.push({
            ...goods,
            sku_info_list: formatSkuInfoList,
          });
        }
      }
    })();
  });
  await Promise.all(promiseArray);

  return list;
}

async function filterGoodsDataByPlatformPriceMap({
  enableGoodsData,
  platformPricePercentage,
}: {
  enableGoodsData: any[];
  platformPricePercentage: number;
}): Promise<any[]> {
  const data = enableGoodsData.reduce((list, item) => {
    const { supply_price_info: skc_supply_price_info, sku_info_list } = item;
    if (skc_supply_price_info) {
      const {
        intercept_supply_price: minPrice,
        max_supply_price: maxPrice,
        supply_price,
      } = skc_supply_price_info || {};
      const __finallyPrice = Number(
        (
          Number(supply_price) *
          ((100 - Number(platformPricePercentage)) / 100)
        ).toFixed(2)
      );
      if (
        minPrice &&
        maxPrice &&
        supply_price &&
        __finallyPrice > Number(minPrice) &&
        __finallyPrice < Number(maxPrice)
      ) {
        list.push({
          ...item,
          __finallyPrice,
        });
      }
    } else {
      const formatSkuInfoList: any = [];
      sku_info_list.forEach((skuInfoItem: any) => {
        const { supply_price_info: sku_supply_price_info } = skuInfoItem;
        if (sku_supply_price_info) {
          const {
            intercept_supply_price: minPrice,
            max_supply_price: maxPrice,
            supply_price,
          } = sku_supply_price_info || {};
          const __finallyPrice = Number(
            (
              Number(supply_price) *
              ((100 - Number(platformPricePercentage)) / 100)
            ).toFixed(2)
          );
          if (
            minPrice &&
            maxPrice &&
            supply_price &&
            __finallyPrice > Number(minPrice) &&
            __finallyPrice < Number(maxPrice)
          ) {
            formatSkuInfoList.push({
              ...skuInfoItem,
              __finallyPrice,
            });
          }
        }
      });
      const isAllMath = formatSkuInfoList.length === sku_info_list.length;

      if (isAllMath) {
        list.push({
          ...item,
          sku_info_list: formatSkuInfoList,
        });
      }
    }

    return list;
  }, []);

  return Promise.resolve(data);
}

async function filterGoodsDataByPriceMap({
  enableGoodsData,
  shopId,
  platform,
  baoyiplus_accessToken,
  multiplierMinInput,
  multiplierMaxInput,
  isOnlyAddGoods,
  priceSource,
  platformPricePercentage,
}: {
  enableGoodsData: any[];
  shopId: string;
  platform: string;
  baoyiplus_accessToken: string;
  multiplierMinInput: number;
  multiplierMaxInput: number;
  isOnlyAddGoods: boolean;
  priceSource: string;
  platformPricePercentage: number;
}): Promise<any[]> {
  if (priceSource === "platformPrice") {
    return filterGoodsDataByPlatformPriceMap({
      enableGoodsData,
      platformPricePercentage,
    });
  } else if (priceSource === "erpPrice") {
    return filterGoodsDataByErpPriceMap({
      enableGoodsData,
      shopId,
      platform,
      baoyiplus_accessToken,
      multiplierMinInput,
      multiplierMaxInput,
      isOnlyAddGoods,
    });
  }
  return Promise.resolve(enableGoodsData);
}

// 获取shein后台商品列表并根据ERP价格和填写的倍率获取最后验证通过的商品
async function getGoodsListData({
  data,
  startPageNum = 1,
}: {
  data: any;
  startPageNum: number;
}) {
  const {
    shopId,
    platform,
    baoyiplus_accessToken,
    multiplierMinInput,
    multiplierMaxInput,
    addGoodsNumber,
    addGoodsNumber2,
    pluginMode,
    isOnlyAddGoods = false,
    priceSource,
    platformPricePercentage,
  } = data;
  const uploadNumber =
    pluginMode === "quickMode"
      ? Number(addGoodsNumber2) || 500
      : Number(addGoodsNumber) || 500;

  const payloadData = await getPayloadData();
  const page_size = 500;
  const goodsList: any[] = [];
  let totalPage = 0;
  let shouldStop = false;

  // 首先获取第一页来确定总页数（只获取count，不处理数据）
  const firstPageData = await getGoodsList({
    ...payloadData,
    page_num: 1,
    page_size: 1,
  });

  if (firstPageData?.info?.meta?.count) {
    const total = Number(firstPageData.info.meta.count);
    totalPage = Math.ceil(total / page_size);
  }
  // 创建任务数组，从第1页开始到最后一页，统一在循环中处理
  if (totalPage > 0) {
    const tasks = [];
    for (let page_num = startPageNum; page_num <= totalPage; page_num++) {
      tasks.push(async () => {
        if (shouldStop) return;
        try {
          const resData = await getGoodsList({
            ...payloadData,
            page_num,
            page_size,
          });

          const goodsDataList = (resData?.info?.data || []) as any[];
          const enableGoodsData: any[] = goodsDataList.filter((goods) => {
            return !goods?.error_code;
          });

          if (enableGoodsData.length) {
            const filteredGoodsData = await filterGoodsDataByPriceMap({
              enableGoodsData,
              shopId,
              platform,
              baoyiplus_accessToken,
              multiplierMinInput,
              multiplierMaxInput,
              isOnlyAddGoods,
              priceSource,
              platformPricePercentage,
            });
            goodsList.push(...filteredGoodsData);
          }

          // 检查是否达到目标数量
          if (goodsList.length >= uploadNumber) {
            shouldStop = true;
          }
        } catch (error) {
          console.log("error ", error);
        }
      });
    }

    // 并发执行所有任务
    await concurrentExecutor.execute(tasks);
  }

  // 最后统一处理数量限制
  const finalGoodsList = goodsList.slice(0, uploadNumber);
  return finalGoodsList;
}

function createActivity(params: any) {
  return new Promise((resolve, reject) => {
    fetch(
      `${originUrl}/mrs-api-prefix/promotion/simple_platform/create_activity`,
      {
        method: "POST",
        headers: {
          "Content-Type": "application/json",
        },
        body: JSON.stringify(params),
      }
    )
      .then((res) => {
        res
          .json()
          .then((resData) => {
            if (Number(resData.code) === 0) {
              resolve(true);
            } else {
              reject(resData?.msg || "创建活动接口请求错误");
            }
          })
          .catch((error) => {
            reject(error || `创建活动接口解析返回错误， res => ${res}`);
          });
      })
      .catch((error) => {
        reject(error || "创建活动接口请求错误");
      });
  });
}

async function startQuickMode({ action, data }: { action: string; data: any }) {
  const baoyiCustomPlugLoadingManager = (window as any)
    .baoyiCustomPlugLoadingManager;
  if (baoyiCustomPlugLoadingManager) {
    baoyiCustomPlugLoadingManager.show("正在获取商品数据...");
  }
  const storage = await chrome.storage.sync.get(["baoyiplus_accessToken"]);
  const { baoyiplus_accessToken = "" } = storage;
  if (baoyiplus_accessToken) {
    try {
      const startTime = Math.floor(Date.now() / 1000);

      const finalGoodsList = await getGoodsListData({
        data: {
          ...data,
          baoyiplus_accessToken,
        },
        startPageNum: 1,
      });
      if (!finalGoodsList.length) {
        if (baoyiCustomPlugLoadingManager) {
          baoyiCustomPlugLoadingManager.hide();
        }
        alert("暂无符合条件的商品可以添加");
        return;
      }
      const createBaseParams: any = await getSemiPlatformCreateActivePayload();
      if (!createBaseParams) {
        if (baoyiCustomPlugLoadingManager) {
          baoyiCustomPlugLoadingManager.hide();
        }
        alert("获取不到创建活动的参数");
        return;
      }
      const { activity_base_info_request, pricing_type } = createBaseParams;

      // 活动限量，为1则不限量。2则为限量
      const isActiveStockLimit =
        Number(activity_base_info_request.sub_type_id) === 2;

      const add_cost_and_stock_info_list = finalGoodsList.map((goodsItem) => {
        const {
          sku_info_list,
          effective_center_list,
          supply_price_info,
          is_sale_attribute,
          __finallyPrice,
          effective_promotion_id_list,
          skc,
          inventory_num,
        } = goodsItem;
        const add_sku_list = sku_info_list.map((skuItem: any) => {
          const { sku, supply_price_info, __finallyPrice } = skuItem;
          const { supply_price = 0, max_supply_price = 0 } =
            supply_price_info || {};
          return {
            cost_price: supply_price, // 多SKU则有值。单SKU为0， 下同
            max_product_act_price: max_supply_price,
            product_act_price: __finallyPrice || 0,
            sku,
          };
        });
        const { supply_price = 0, max_supply_price = 0 } =
          supply_price_info || {};
        return {
          add_sku_list,
          attend_num: isActiveStockLimit ? inventory_num : 0, // 活动库存，如果不限量为0，如果是限量则使用库存
          center_list: effective_center_list,
          is_sale_attribute,
          cost_price: supply_price,
          max_product_act_price: max_supply_price,
          product_act_price: __finallyPrice || 0, // 多SKU就是0
          promotion_id_list: effective_promotion_id_list,
          skc,
          stock_num: inventory_num,
        };
      });
      const addCostAndStockInfoListChunkList = chunkArray(
        add_cost_and_stock_info_list,
        500
      );
      for (let i = 0; i < addCostAndStockInfoListChunkList.length; i++) {
        const { zone_start_time } = activity_base_info_request;
        const currentTime = Math.floor(Date.now() / 1000);
        const diffTime = currentTime - startTime;
        let nowZoneStartTime = "";
        if (zone_start_time) {
          const baseTs = parseDateTimeToTs(zone_start_time);
          const newTs = baseTs + diffTime;
          nowZoneStartTime = formatTsToDateTime(newTs);
        } else {
          nowZoneStartTime = "";
        }
        const timeText = getCurrentTimeText();
        const params = {
          activity_base_info_request: {
            ...activity_base_info_request,
            act_name: `限时折扣${timeText}`,
            zone_start_time: nowZoneStartTime || zone_start_time,
          },
          add_cost_and_stock_info_list: addCostAndStockInfoListChunkList[i],
          pricing_type,
        };
        await createActivity(params);
      }

      baoyiCustomPlugLoadingManager.hide();

      showCustomDialog({
        message: "创建成功",
        buttons: [
          {
            label: "前往查看",
            onClick: () => {
              window.location.href = `${originUrl}/#/mrs/tools/list/1/0`;
            },
          },
          {
            label: "继续创建",
            onClick: () => {
              window.location.href = `${originUrl}/#/mrs/tools/activity/obm-time-limit-detail/add?toolId=30`;
            },
          },
        ],
      });
    } catch (error) {
      alert(error);
      baoyiCustomPlugLoadingManager.hide();
    }
  } else {
    alert("获取不到登录信息，请登录后重试");
    baoyiCustomPlugLoadingManager.hide();
  }
}

export default {
  manualVerifyPageGoods,
  startQuickMode,
};
